package com.suning.sawp.web.filter;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.intf.promotion.InnerCouponService;
import com.suning.sawp.service.util.SCMConfigUtil;

/**
 * 
 * djToken过滤器<br>
 * 〈功能详细描述〉
 *
 * @author 12061818
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class DjTokenFilter implements Filter {

	/***
	 * token校验不过，非法请求，返回提示
	 */
	private static final String REQ_REJECT_MSG = "{\"retFlag\":\"0\",\"errorCode\":\"1000\",\"errorMessage\":\"非法请求\"}";
	
	private static final String REQ_BLACK_LIST_REJECT_MSG = "{\"retFlag\":\"0\",\"errorCode\":\"0047\",\"errorMessage\":\"你的账号存在风险，已经被禁用，请联系客服\"}";

	private static final Logger LOGGER = LoggerFactory.getLogger(DjTokenFilter.class);

	// 黑名单处理（以前的内部券黑名单，找时间把他移走单独拆到公用基础服务中去）
	private InnerCouponService innerCouponService;
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		// passport登录标识，默认已登录
		final String staffId = httpRequest.getRemoteUser();
		LOGGER.debug("-------------------------当前登录的工号为:{}----------------", staffId);
		final String scmVaule = SCMConfigUtil.getConfig(ConfigConstants.STAFF_PREFIX + staffId);

		String rejectMsg = REQ_REJECT_MSG;
		if (StringUtils.isNotBlank(staffId)) {
		    // 判断此工号是否在黑名单中，如果是的话拒绝访问
		    if (innerCouponService.isBlackList(staffId)) {
		        LOGGER.warn("DjTokenFilter 此工号在黑名单中，staffId:{}", staffId);
		        rejectMsg = REQ_BLACK_LIST_REJECT_MSG;
		    } else {
		        // 不在黑名单中，将从passport取得的员工工号传递过去
	            chain.doFilter(new DjTokenRequestWraper(httpRequest, new Principal() {
	                @Override
	                public String getName() {
	                    if (StringUtils.isNotBlank(scmVaule)) {
	                        return scmVaule;
	                    }
	                    return staffId;
	                }
	            }), httpResponse);

	            return;
		    }
		} else {
		    LOGGER.warn("DjTokenFilter 调用passport未能获取工号");
		}
		// token校验失败，则表明客户端本次请求非法，拒绝访问
		httpResponse.setContentType("application/json;charset=utf-8");
		httpResponse.addHeader("Cache-Control", "no-cache");
		httpResponse.getOutputStream().write(rejectMsg.getBytes("UTF-8"));
		httpResponse.getOutputStream().flush();
		httpResponse.getOutputStream().close();

	}

	@Override
	public void destroy() {
		LOGGER.info("destroy enter");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		LOGGER.info("init enter");
		ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(
                filterConfig.getServletContext());
        if (null == innerCouponService) {
            innerCouponService = ac.getBean(InnerCouponService.class);
        }
	}

}
